package cn.siat.gene.service.impl;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.siat.common.core.exception.ServiceException;
import cn.siat.common.security.utils.SecurityUtils;
import cn.siat.gene.domain.Programme;
import cn.siat.gene.mapper.ProgrammeMapper;
import cn.siat.gene.domain.Template;
import cn.siat.gene.mapper.TemplateMapper;
import cn.siat.gene.service.TemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.Date;
import java.util.List;

@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, Template> implements TemplateService {
    @Autowired
    private TemplateMapper templateMapper;
    @Autowired
    private ProgrammeMapper programmeMapper;
    @Value("${path.sequence}")
    private String sequencePath;
    @Value("${path.template}")
    private String templatePath;

    public List<Template> getTemplateList(String name) {
        List<Template> templateList = templateMapper.getTemplateList(SecurityUtils.getUserId(),name);
        return templateList;
    }

    @Override
    public Boolean checkName(String name,String id) {
        QueryWrapper<Template> wrapper = new QueryWrapper<Template>()
                .eq("name", name)
                .eq("creater", SecurityUtils.getUserId());
        //编辑弹窗不校验本身
        if(id!=null){
            wrapper.ne("id", id);
        }
        Long count = templateMapper.selectCount(wrapper);
        if(count == null || count == 0L){
            return  false;
        }
        return true;
    }

    @Override
    @Transactional
    public void saveTemplate(Template template) {
        template.setCreater(SecurityUtils.getUserId());
        template.setId(IdUtil.getSnowflakeNextIdStr());
        template.setCreateTime(new Date());

        String separator = File.separator;
        String programmeId = template.getProgrammeId();
        Programme programme = programmeMapper.selectById(programmeId);
        String sourceFileName = programme.getSourceFileName();
        //本地文件路径
        String localFilePath = sequencePath + separator + programmeId + separator + sourceFileName;
        File localFile = new File(localFilePath);
        //如果本地文件不存在, 说明没打包
        if(!localFile.exists()){
            //如果存在多个文件说明是浏览视图打包
            if(sourceFileName.contains(",")){
                throw new ServiceException("当前方案为浏览视图方案，不支持保存为模板！");
            }
            throw new ServiceException("找不到该方案文件！可能未打包!");
//            localFile = new File(sequencePath + separator + programmeId + separator + programme.getSourceFileName());
//            if(!localFile.exists()){
//                throw new ServiceException("找不到该方案文件！");
//            }
        }
        //模板文件路径
        String templateFilePath = templatePath + separator + template.getId() + ".gbff";
        File templateFile = FileUtil.copy(localFile, new File(templateFilePath), true);
        if(!templateFile.exists()){
            throw new ServiceException("创建模板文件失败！");
        }
        template.setTemplateFileName(template.getId() + ".gbff");
        save(template);
    }

    /**
     * 删除模板
     * @param id
     */
    @Override
    @Transactional
    public void deleteTemplate(String id) {
        if(templateMapper.selectById(id) == null){
            throw new ServiceException("删除模板不存在！");
        }
        boolean isSuccess = removeById(id);
        if(isSuccess){
            FileUtil.del(new File(templatePath + File.separator + id + ".gbff"));
        }
    }

    /**
     * 判断方案是否是浏览视图
     */
    @Override
    public Integer checkIsBrowsingMode(String id) {
        Programme programme = programmeMapper.selectById(id);
        if(programme == null){
            throw new ServiceException("该方案不存在！");
        }
        String separator = File.separator;
        String sourceFileName = programme.getSourceFileName();
        //本地文件路径
        String localFilePath = sequencePath + separator + id + separator + sourceFileName;
        File localFile = new File(localFilePath);
        //如果本地文件不存在, 说明没打包
        if(!localFile.exists()){
            //如果存在多个文件说明是浏览视图打包
            if(sourceFileName.contains(",")){
                return 1;
            }
            return 0;
        }
        return null;
    }
}
